package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@RabbitListener(queues = "order.release.order.queue")
@Service
public class MqListener {

    @Autowired
    OrderService orderService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 自动关闭订单
     */
    @RabbitHandler
    public void closeOrder(OrderEntity orderEntity, Message message, Channel channel) throws IOException {
//        System.out.println("即将关闭订单："+order.getOrderSn());
        log.info("即将关闭订单：" + orderEntity.getOrderSn());
        try {
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//            System.out.println("订单关闭成功");
            log.info("订单关闭成功,消息消费成功");


        } catch (Exception exception) {
            //消息重新入队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            log.info("订单关闭失败，消息重新入队列");
        }
    }


}
